package com.example.demo.common;

import com.alibaba.fastjson.JSON;

/**
 * @Author: zhuchunfeng
 * @Description
 * @Date: 2020/5/14 10:35
 * Copyright (c) 2019 北京新媒传信科技有限公司
 */
public class ApiResult<T> {
    private int code;
    private String desc;
    private T result;
    private Object extra;
    private int total;

    public ApiResult() {
    }

    public ApiResult(int code, String desc, T result, Object extra) {
        super();
        this.code = code;
        this.desc = desc;
        this.result = result;
        this.extra = extra;
    }

    public ApiResult(int code, String desc, T result) {
        super();
        this.code = code;
        this.desc = desc;
        this.result = result;
    }

    public ApiResult(int code, String desc) {
        super();
        this.code = code;
        this.desc = desc;
        this.result = null;
    }

    public ApiResult(ApiCode apiCode) {
        super();
        this.code = apiCode.getCode();
        this.desc = apiCode.getDesc();
        this.result = null;
    }

    public ApiResult(ApiCode apiCode, T result) {
        super();
        this.code = apiCode.getCode();
        this.desc = apiCode.getDesc();
        this.result = result;
    }

    public ApiResult(ApiCode apiCode, T result, int total) {
        super();
        this.code = apiCode.getCode();
        this.desc = apiCode.getDesc();
        this.result = result;
        this.total = total;
    }

    public int getCode() {
        return code;
    }

    public String getDesc() {
        return desc;
    }

    public T getResult() {
        return result;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    public static <T> ApiResult<T> build(int status, String desc, T result) {
        return new ApiResult<>(status, desc, result);
    }

    public static ApiResult<?> build(int status, String desc) {
        return new ApiResult<>(status, desc);
    }

    public static <T> ApiResult<T> error(int status) {
        return new ApiResult<>(status, "Error");
    }

    public static <T> ApiResult<T> error(int status, T result) {
        return new ApiResult<>(status, "Error", result);
    }

    public static <T> ApiResult<T> success() {
        return new ApiResult<>(ApiCode.STATUS_OK);
    }

    public static <T> ApiResult<T> success(T result) {
        return new ApiResult<>(ApiCode.STATUS_OK, result);
    }

    public static <T> ApiResult<T> success(T result, int total) {
        return new ApiResult<>(ApiCode.STATUS_OK, result, total);
    }

    public static <T> ApiResult<T> result(Boolean r) {
        return new ApiResult<>(r ? ApiCode.STATUS_OK : ApiCode.STATUS_INTERNAL_ERROR);
    }

    public Object getExtra() {
        return extra;
    }

    public void setExtra(Object extra) {
        this.extra = extra;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }
}